package com.devilloki.viki.overspeedalert.services;

import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.ActivityCompat;

import com.devilloki.viki.overspeedalert.Events.ConfigEvent;
import com.devilloki.viki.overspeedalert.Events.GpsInfoEvent;
import com.devilloki.viki.overspeedalert.tools.MY_NAMES;
import com.devilloki.viki.overspeedalert.tools.SettingsHelper;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/** 计算平均速度的srvice
 * Created by viki on 2016/3/20.
 */
public class AlertService extends Service implements LocationListener {

    private LocationManager locationManager = null;

    // 最小时间设置为1,距离设置为0
    // 可以实时更新速度,并且设置一个阀值,当速度小于某个值的时候,认为位置没有变化
    // 避免位置没有变化的时候,速度还有显示
    /**
     * 更新GPS信息的最小时间
     */
    private long minTimeUpdateGPS = 1;
    /**
     * 更新GPS信息的最短距离
     */
    private float minDistanceUpdateGPS = 0;
    /**
     * 用于在SharedPreferences存储数据的工具类
     */
    private SettingsHelper setting = null;

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
        setting = new SettingsHelper(this);
        // 获取位置管理服务
        String serviceName = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) this.getSystemService(serviceName);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, minTimeUpdateGPS, minDistanceUpdateGPS, this);
        //初始化行程
        initTrack();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 将Location转换为Event,并通过eventbus发布
     * @param location 需要发布的Location
     */
    private void postEvent(Location location) {
        if (location != null) {
            // 通过EventBus 将GPS信息post
            // 该 Event将会在DisplayFragment中接收
            GpsInfoEvent event = new GpsInfoEvent();
            event.setLongitude(location.getLongitude());
            event.setLatitude(location.getLatitude());
            event.setAltitude(location.getAltitude());
            event.setSpeed(location.getSpeed());
            EventBus.getDefault().post(event);
        }

    }

    /**
     * 重置行程
     */
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onEventStartTimeTask(ConfigEvent event) {

        if (event.isStartCal()) {
            initTrack();
        }
    }

    /**
     * 重置行程
     */
    private void initTrack() {
        //将行程开始的经纬度,时间等置0
        setting.setString(MY_NAMES.KEY_START_LNG, MY_NAMES.DATA_Default_LngAndLat);
        setting.setString(MY_NAMES.KEY_START_LAT, MY_NAMES.DATA_Default_LngAndLat);
        setting.setString(MY_NAMES.KEY_START_TIME, MY_NAMES.DATA_Default_LngAndLat);
        setting.setString(MY_NAMES.KEY_TRACK_DISTANCE, MY_NAMES.DATA_Default_LngAndLat);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        locationManager.removeUpdates(this);
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onLocationChanged(Location location) {
        postEvent(location);
        //=================================================
        //上一个坐标点的经纬度
        double preLoctionlng=Double.valueOf(setting.getString(MY_NAMES.KEY_START_LNG, MY_NAMES.DATA_Default_LngAndLat));
        double preLoctionlat=Double.valueOf(setting.getString(MY_NAMES.KEY_START_LAT, MY_NAMES.DATA_Default_LngAndLat));
        double distance=Double.valueOf(setting.getString(MY_NAMES.KEY_TRACK_DISTANCE,MY_NAMES.DATA_Default_LngAndLat));
        // ================================================
        // 如果 SharedPreferences 中没有数据,则默认为0,所以这里的double数据类型用!=0来判断
        if(preLoctionlng!=0){
            // 如果 SharedPreferences 中有经纬度,则计算当前坐标与上一个坐标的直线距离
            distance+= calculateLineDistance(preLoctionlng,preLoctionlat,
                    location.getLongitude(),location.getLatitude());
        }

        if(0==Double.valueOf(setting.getString(MY_NAMES.KEY_START_TIME,MY_NAMES.DATA_Default_LngAndLat))){
            //如果 SharedPreferences 中没有行程的起始时间,将当前时间做为行程的起始时间
            setting.setString(MY_NAMES.KEY_START_TIME,String.valueOf(System.currentTimeMillis()));
        }
        // ================================================
        //将行程的总里程及当前坐标写入SharedPreferences
        setting.setString(MY_NAMES.KEY_START_LNG,String.valueOf(location.getLongitude()));
        setting.setString(MY_NAMES.KEY_START_LAT,String.valueOf(location.getLatitude()));
        setting.setString(MY_NAMES.KEY_TRACK_DISTANCE,String.valueOf(distance));
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    /**
     * 计算两个GPS坐标点之间的直线距离
     * @param paramLng1 第一个坐标点的经度
     * @param paramLat1 第一个坐标点的纬度
     * @param paramLng2 第二个坐标点的经度
     * @param paramLat2 第二个坐标点的纬度
     * @return 直线距离(单位:m)
     */
    private float calculateLineDistance(double paramLng1, double paramLat1,double paramLng2,double paramLat2)
    {
        double d1 = 0.01745329251994329D;
        double d2 = paramLng1;
        double d3 = paramLat1;
        double d4 = paramLng2;
        double d5 = paramLat2;
        d2 *= d1;
        d3 *= d1;
        d4 *= d1;
        d5 *= d1;
        double d6 = Math.sin(d2);
        double d7 = Math.sin(d3);
        double d8 = Math.cos(d2);
        double d9 = Math.cos(d3);
        double d10 = Math.sin(d4);
        double d11 = Math.sin(d5);
        double d12 = Math.cos(d4);
        double d13 = Math.cos(d5);
        double[] arrayOfDouble1 = new double[3];
        double[] arrayOfDouble2 = new double[3];
        arrayOfDouble1[0] = (d9 * d8);
        arrayOfDouble1[1] = (d9 * d6);
        arrayOfDouble1[2] = d7;
        arrayOfDouble2[0] = (d13 * d12);
        arrayOfDouble2[1] = (d13 * d10);
        arrayOfDouble2[2] = d11;
        double d14 = Math.sqrt((arrayOfDouble1[0] - arrayOfDouble2[0]) * (arrayOfDouble1[0] - arrayOfDouble2[0]) + (arrayOfDouble1[1] - arrayOfDouble2[1]) * (arrayOfDouble1[1] - arrayOfDouble2[1]) + (arrayOfDouble1[2] - arrayOfDouble2[2]) * (arrayOfDouble1[2] - arrayOfDouble2[2]));

        return (float)(Math.asin(d14 / 2.0D) * 1.27420015798544E7D);
    }


}
